/**
 * 
 */
package cc.telecomdigital.tdstock.activity.groups.more.push.activity;

import android.content.Intent;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebSettings.RenderPriority;
import android.widget.Button;
import cc.telecomdigital.tdstock.CustomizeDialog;
import cc.telecomdigital.tdstock.ITDLApplication;
import cc.telecomdigital.tdstock.ProgressDialog;
import cc.telecomdigital.tdstock.R;
import cc.telecomdigital.tdstock.SystemInfo;
import cc.telecomdigital.tdstock.CommonDefn.ModeType;
import cc.telecomdigital.tdstock.Framework.UniqueItem.TDStockLog;
import cc.telecomdigital.tdstock.Framework.UniqueItem.NetworkChangeListener.CONNECT_TYPE;
import cc.telecomdigital.tdstock.Tools.ActivityGroupController;
import cc.telecomdigital.tdstock.activity.BaseActivity;
import cc.telecomdigital.tdstock.activity.groups.MoreGroup;
import cc.telecomdigital.tdstock.activity.groups.more.MoreActivity;
import cc.telecomdigital.tdstock.activity.groups.more.push.client.Constants;
import cc.telecomdigital.tdstock.activity.groups.more.push.client.NotifierCounter;
import cc.telecomdigital.tdstock.activity.groups.more.push.util.MessageHistoryListAsyncTask;
import cc.telecomdigital.tdstock.activity.groups.more.push.util.WebViewCopy;

/**  
 *   
 * Project：tdstock3
 * Package：cc.telecomdigital.tdstock.activity.groups.more.push
 * Class：MessageHistoryList
 * Description：  
 * Creater：hunter
 * CreateTime：Oct 13, 2011 3:41:24 PM 
 * Modifier ：hunter
 * Modify time：Oct 13, 2011 3:41:24 PM 
 * Modify Remarks：  
 * @version   
 *   
 */
public class MessageHistoryListActivity extends BaseActivity
{

	protected static final String	TAG					= MessageHistoryListActivity.class
														.getSimpleName();
	// public static final String INTENT_KEY_COME_FROM = "Come.From";
	public static final String	COME_FROM_ENTRY_CONTENT	= MessageContentActivity.class
														.getSimpleName();

	//private  TextView  _txt;
	private WebView			_webView;
	private Button				_toolBtnReturn;
	private boolean			isFinished;
	//private static  int i=0;

	private WebViewCopy			copy;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		if (((ITDLApplication) this.getApplicationContext()).getModeType() == ModeType.DELARY)
		{
			setContentView(R.layout.more_message_delay);
			Button _toolBtnReturn = (Button) findViewById(R.id.more_message_returnbtn);
			_toolBtnReturn.setOnClickListener(new OnClickListener()
			{
				@Override
				public void onClick(View v)
				{
					Intent intent = new Intent(getApplicationContext(),
							MoreActivity.class);
					intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP| Intent.FLAG_ACTIVITY_NO_USER_ACTION);
					SwitchForwardActivity(MoreActivity.class, intent);
				}
			});

		}
		else
		{
			this.setContentView(R.layout.stock_message_list);
			_toolBtnReturn = (Button) findViewById(R.id.more_message_return);
			_toolBtnReturn.setFocusable(true);
			_toolBtnReturn.setClickable(true);
			_toolBtnReturn.setOnClickListener(new OnClickListener()
			{
				@Override
				public void onClick(View v)
				{
					/**/
					Intent intent = new Intent(getApplicationContext(),
											MoreActivity.class);
									intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP| Intent.FLAG_ACTIVITY_NO_USER_ACTION);
									SwitchForwardActivity(MoreActivity.class, intent);
				}
			});
			/*ViewGroup viewGroup=(ViewGroup)findViewById(R.id.web_list);
			_webView =new WebView(this.getParent()==null?this:this.getParent());*/
			_webView = (WebView) findViewById(R.id.webview);
			WebSettings webSettings = _webView.getSettings();

			webSettings.setBuiltInZoomControls(true);

			//			webSettings.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
			//			webSettings.setUseWideViewPort(true);
			webSettings.setRenderPriority(RenderPriority.HIGH);
			webSettings.setJavaScriptEnabled(true);
			_webView.setHorizontalScrollBarEnabled(false);

			_webView.setWebViewClient(new WebViewClient()
			{
				public boolean shouldOverrideUrlLoading(WebView view,
						String url)
				{
					TDStockLog.d(TAG, url);

					if (!SystemInfo
							.isNetworkingConnected(MessageHistoryListActivity.this))
					{
						new CustomizeDialog(
								MessageHistoryListActivity.this
										.getParent() == null ? MessageHistoryListActivity.this
										: MessageHistoryListActivity.this
												.getParent(),
								getString(R.string.info),
								getString(R.string.service_not_available),
								getString(R.string.ok)).show();
						return true;
					}

					if (url.indexOf("&id=") != -1)
					{
						forwardMessageContentActivity(url);
					}
					else
					{
						_webView.loadUrl(url);
					}

					return true;
				}
			});

			/*LinearLayout.LayoutParams params=new LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.FILL_PARENT);
			
			viewGroup.addView(_webView,params);*/
			copy = new WebViewCopy(this, _webView);
		}

	}

	@Override
	protected void onResume()
	{
		// TODO Auto-generated method stub
		super.onResume();
		//setWebViewContent();
		//postDelayed();
		if (((ITDLApplication) this.getApplicationContext()).getModeType() == ModeType.DELARY)
		{

		}
		else
		{

			NotifierCounter.getInstnace().clearCounter();
			//CacheManager.CacheResult cr=CacheManager.getCacheFile("", null);
			if (COME_FROM_ENTRY_CONTENT.equals(this.getIntent()
					.getStringExtra(Constants.INTENT_KEY_COME_FROM)))
			{
				//do nothing if it come from MessageContentActivity
				TDStockLog
						.d(TAG,
								"come from MessageContentActivity and  back to my self.");
				return;
			}

			TDStockLog.d(TAG, "ready to fetch data again!");
			getMessageHistoryListForHttpPost();

		}

	}

	private void getMessageHistoryListForHttpPost()
	{
		new MessageHistoryListAsyncTask(this.getParent(), "")
		{
			private String	temp;

			@Override
			protected Void doInBackground(String... params)
			{
				// TODO Auto-generated method stub
				super.doInBackground(params);
				temp = this.getUrl();
				TDStockLog.e(TAG, "Message History LIst Url:" + temp);
				/*	if(!result.equals("")){
						   setWebViewContent(result);
						   i=1;
						}else{
							setWebContextDefault();
						}*/
				return null;
			}

			@Override
			protected void onPostExecute(Void result)
			{
				super.onPostExecute(result);
				//Log.d(TAG, result);
				TDStockLog.d(TAG, temp == null ? "temp is null" : temp);
				if (!"".equals(temp) && null != temp)
				{
					setWebViewContent(temp);
					isFinished = true;
				}
				else
				{
					isFinished = false;
					setWebContextDefault();
				}

			}

		}.execute();
	}

	/* (non-Javadoc)
	 * @see cc.telecomdigital.tdstock.Framework.ActivityGroup_Framework#GetActivityGroupController()
	 */
	@Override
	protected ActivityGroupController GetActivityGroupController()
	{
		// TODO Auto-generated method stub
		return MoreGroup.GetActivityGroupHostControl();
	}

	@Override
	protected void onPause()
	{
		// TODO Auto-generated method stub
		super.onPause();
		if (((ITDLApplication) this.getApplicationContext()).getModeType() == ModeType.DELARY)
		{

		}
		else
		{
			ProgressDialog.dismissAll();
		}
	}

	/*	//go MessageContentActivity  but it is not from webview
		private void forwardMessageContentActivity(){
			Log.d(TAG, "forwardMessageContentActivity");
			Intent intent = new Intent(getApplicationContext(),
					MessageContentActivity.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP| Intent.FLAG_ACTIVITY_NO_USER_ACTION);
			SwitchForwardActivity(MessageContentActivity.class, intent);
		}*/
	/**
	 * go MessageContentActivity From WebVIew
	 */
	private void forwardMessageContentActivity(String url)
	{
		if (null == url || "".equals(url))
		{
			return;
		}
		TDStockLog.d(TAG, "forwardPushActivity");
		Intent intent = new Intent(getApplicationContext(),
				MessageContentActivity.class);
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NO_USER_ACTION);
		intent.putExtra(Constants.INTENT_KEY_COME_FROM, TAG);
		intent.putExtra(Constants.INTENT_KEY_DETAIL_MESSAGE_URL, url);
		MessageContentActivity.type = 2;
		SwitchForwardActivity(MessageContentActivity.class, intent);
	}

	/*private void forwardMessageContentActivity(String url){
		String id="";
		try{
		    id=url.substring(url.indexOf("&id=")+4, url.length());
		}catch(Exception e){
			id=_id_URL;
		}finally{
			Log.d(TAG, "forwardPushActivity");
			Intent intent = new Intent(getApplicationContext(),
					MessageContentActivity.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP| Intent.FLAG_ACTIVITY_NO_USER_ACTION);
			intent.putExtra("_detail_url_id", id);
			id="";
			SwitchForwardActivity(MessageContentActivity.class, intent);
		}
	}*/
	//set webview content
	/*	public void setWebViewContent(){
			  if (_webView != null)
				{
					Log.d(TAG, "content=" + _content);
					_webView.getSettings().setBuiltInZoomControls(true);
					_webView.getSettings().setJavaScriptEnabled(true);
					_webView.loadDataWithBaseURL(null, _content, "text/html","utf-8", null);
					Data.message_list_html="";
				}
		}*/
	public void setWebViewContent(final String url)
	{
		if (_webView != null)
		{

			//_webView.getSettings().setBuiltInZoomControls(true);
			//_webView.getSettings().setJavaScriptEnabled(true);
			_webView.postDelayed(new Runnable()
			{

				@Override
				public void run()
				{
					// TODO Auto-generated method stub
					_webView.loadUrl(url);
				}
			}, 400);/*_webView.loadUrl(url);*/
		}
	}

	public void setWebContextDefault()
	{
		if (_webView != null)
		{
			String summary = "<html><head></head><body>"
					+ this.getString(R.string.service_not_available)
					+ "</body></html>";
			TDStockLog.d(TAG, "content=" + summary);
			//_webView.getSettings().setBuiltInZoomControls(true);
			//_webView.getSettings().setJavaScriptEnabled(true);
			_webView.loadDataWithBaseURL(null, summary, "text/html",
					"utf-8", null);
		}
	}

	@Override
	protected void onNewIntent(Intent intent)
	{
		super.onNewIntent(intent);
		getIntent().putExtras(intent); //update the current intent
	}

	public void NetworkChange_Response(CONNECT_TYPE iConnect,
			NetworkInfo iNetInfo)
	{

		//super.NetworkChange_Response(iConnect, iNetInfo);
		if (iNetInfo.isAvailable() || iNetInfo.isConnected())
		{
			if (((ITDLApplication) this.getApplicationContext())
					.getModeType() == ModeType.DELARY)
			{

			}
			else if (!isFinished)
			{
				getMessageHistoryListForHttpPost();
			}
		}

	}

	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo)
	{
		copy.onCreateContextMenu(menu, v, menuInfo, COPY,
				getString(R.string.copy));
		super.onCreateContextMenu(menu, v, menuInfo);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		super.onCreateOptionsMenu(menu);
		if (((ITDLApplication) this.getApplicationContext()).getModeType() == ModeType.DELARY)
		{

		}
		else
		{
			menu.add(0, COPY, 0, getString(R.string.copy));
			MenuItem mItem = menu.findItem(COPY);
			mItem.setIcon(R.drawable.copy32x32);
		}
		return true;
	}

	@Override
	public boolean onMenuItemSelected(int c, MenuItem iItem)
	{
		TDStockLog.d(TAG, "onMenuItemSelected");
		super.onMenuItemSelected(c, iItem);
		if (iItem.getItemId() == COPY && _webView != null)
		{
			//WebViewCopy.emulateShiftHeld(_webView);
			WebViewCopy.selectAndCopyText(_webView);
		}

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		super.onOptionsItemSelected(item);
		TDStockLog.d(TAG, "onOptionsItemSelected");
		if (item.getItemId() == COPY && _webView != null)
		{
			WebViewCopy.selectAndCopyText(_webView);
		}
		return true;
	}

	@Override
	public void onBackPressed()
	{
		_toolBtnReturn.performClick();
	}

}
